package com.canbot.u05.activity.shoppingGuide.codeMarketing;

import android.app.Dialog;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.TextView;

import com.alibaba.fastjson.JSON;
import com.canbot.u05.R;
import com.canbot.u05.activity.BaseActivityNoTitle;
import com.canbot.u05.activity.presidemode.eventbus.AudioEvent;
import com.canbot.u05.bean.Audio;
import com.canbot.u05.bean.JsonResponse;
import com.canbot.u05.socket.IpMsgConst;
import com.canbot.u05.socket.MsgSendUtils;
import com.canbot.u05.socket.MsgType;
import com.canbot.u05.utils.Logger;
import com.canbot.u05.utils.OkHttpUtils;
import com.canbot.u05.utils.ToastTools;
import com.canbot.u05.widget.LoadingDialogUtils;

import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

public class CodeChooseAudioActivity extends BaseActivityNoTitle implements AdapterView.OnItemClickListener {

        @BindView(R.id.code_iv_back)
        Button codeIvBack;

        @BindView(R.id.code_iv_ok)
        Button codeIvOk;

        @BindView(R.id.code_voice_gridView)
        GridView codeVoiceGridView;

        private Dialog dialogLoading;

        private String audioPath;

        private int type;

        private List<Audio> data = new ArrayList<>();

        private Audio selectAudio;

        private int lastPosition;

        private ToastTools toastTools;

        private VoiceAdapter adapter;

        private String audioName;

        @Override
        protected void onCreate(Bundle savedInstanceState) {
                super.onCreate(savedInstanceState);
                setContentView(R.layout.activitiy_code_voice_choose);
                ButterKnife.bind(this);
                toastTools = ToastTools.newInstance(this);
                initViews();
                getData();
        }

        private void initViews() {
                codeVoiceGridView.setOnItemClickListener(this);
                Intent intent = getIntent();
                type = intent.getIntExtra("type", AudioEvent.AUDIO_TYPE_AUDIO);
                audioName = intent.getStringExtra("content");
                audioPath = intent.getStringExtra("path");
        }

        private void getData() {
                dialogLoading = LoadingDialogUtils.createLoadingDialog(CodeChooseAudioActivity.this, getResources().getString(R.string.request));
                dialogLoading.show();
                String url = "http://" + IpMsgConst.SOCKET_HOST + ":7755/getAudioList";
                HashMap<String, String> hashMap = new HashMap<>();
                hashMap.put("path", "/uusound");
                OkHttpUtils.upLoadFile(url, hashMap, new OkHttpUtils.OkHttpCallBack() {
                        @Override
                        public void onSuccess(String result) {
                                Log.e("t", result);
                                final JsonResponse strMsgBean = JSON.parseObject(result, JsonResponse.class);
                                Logger.e("save", "onSuccess:" + "http://" + IpMsgConst.SOCKET_HOST + ":7755/" + "strMsgBean.getRc()" + strMsgBean.getRc());
                                if (strMsgBean.getRc() == 0) {
                                        runOnUiThread(new Runnable() {
                                                @Override
                                                public void run() {
                                                        dialogLoading.setCancelable(true);
                                                        dialogLoading.dismiss();
                                                        List<Audio> list = JSON.parseArray(strMsgBean.getResult().toString(), Audio.class);

                                                        Collections.sort(list, new Comparator<Audio>() {
                                                                @Override
                                                                public int compare(Audio audio, Audio t1) {
                                                                        return audio.getName().compareTo(t1.getName());
                                                                }
                                                        });
                                                        for (int i = 0; i < list.size(); i++) {
                                                                Audio audio = list.get(i);
                                                                if (!TextUtils.isEmpty(audioPath)) {
                                                                        if (type == AudioEvent.AUDIO_TYPE_AUDIO && audioPath.equals(audio.getPath())) {
                                                                                audio.setChecked(true);
                                                                                selectAudio = audio;
                                                                                lastPosition = i;
                                                                        }
                                                                }
                                                        }
                                                        setAdapter(list);
                                                        data.addAll(list);
                                                }
                                        });
                                }
                        }

                        @Override
                        public void onFailure() {
                                dialogLoading.dismiss();
                                toastTools.showText(getString(R.string.service_error_hint));
                        }
                });

        }

        private void setAdapter(List<Audio> data) {
                adapter = new VoiceAdapter(this, data);
                codeVoiceGridView.setAdapter(adapter);
        }

        @OnClick({R.id.code_iv_back, R.id.code_iv_ok})
        public void onViewClicked(View view) {
                switch (view.getId()) {
                        case R.id.code_iv_back:
                                finish();
                                break;
                        case R.id.code_iv_ok:
                                if(selectAudio == null) {
                                        toastTools.showText("请先选择对应的音频");
                                        return;
                                }
                                Intent resultIntent = new Intent();
                                resultIntent.putExtra("type", AudioEvent.AUDIO_TYPE_AUDIO);
                                resultIntent.putExtra("content", selectAudio.getName());
                                resultIntent.putExtra("path", selectAudio.getPath());
                                setResult(RESULT_OK, resultIntent);
                                finish();
                                break;
                }
        }

        @Override
        public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                if(data.get(position).isChecked()) {
                        data.get(position).setChecked(false);
                        adapter.updataView(position, codeVoiceGridView);
                        selectAudio = null;
                        //            stopVoice();
                        boolean isSuccess = MsgSendUtils.sendStringMsg(MsgType.STOP_SOUND, "stop");
                        if(!isSuccess) {
                                toastTools.showText(getString(R.string.service_error_hint));
                        }
                } else {
                        data.get(position).setChecked(true);
                        adapter.updataView(position, codeVoiceGridView);
                        selectAudio = data.get(position);
                        boolean isSuccess = MsgSendUtils.sendStringMsg(MsgType.PLAY_SOUND, selectAudio.getPath());
                        if (!isSuccess) {
                                toastTools.showText(getString(R.string.service_error_hint));
                        }
                }
                if(lastPosition != -1 && data.get(lastPosition).isChecked() && lastPosition != position) {
                        data.get(lastPosition).setChecked(false);
                        adapter.updataView(lastPosition, codeVoiceGridView);
                }
                lastPosition = position;
        }

        private class VoiceAdapter extends BaseAdapter {

                private Context context;

                private List<Audio> data;

                private LayoutInflater inflater;

                public VoiceAdapter(Context context, List<Audio> data) {
                        this.context = context;
                        setData(data);
                        inflater = LayoutInflater.from(context);

                }

                private void setData(List<Audio> data) {
                        if (data == null) {
                                data = new ArrayList<>();
                        }
                        this.data = data;
                }

                @Override
                public View getView(int position, View convertView, ViewGroup viewGroup) {
                        ViewHolder holder = null;
                        if (convertView == null) {
                                holder = new ViewHolder();
                                convertView = inflater.inflate(R.layout.code_voice_item, null);
                                holder.fileName = (TextView) convertView.findViewById(R.id.dance_text);
                                holder.checkBox = (ImageView) convertView.findViewById(R.id.cb_dance);
                                convertView.setTag(holder);
                        }
                        else {
                                holder = (ViewHolder) convertView.getTag();
                        }
                        Audio audio = data.get(position);
                        String w = audio.toString();
                        Log.e("t", "" + w);
                        holder.fileName.setText(audio.getName());
                        String e = audio.getName();
                        Log.e("t", "" + e);
                        holder.checkBox.setVisibility(data.get(position).isChecked()?View.VISIBLE:View.GONE);

                        return convertView;
                }

                @Override
                public int getCount() {
                        return data.size();
                }

                @Override
                public Object getItem(int i) {
                        return data.get(i);
                }

                @Override
                public long getItemId(int i) {
                        return i;
                }

                private class ViewHolder {

                        private TextView fileName;

                        private ImageView checkBox;
                }

                /**
                 * 更新控件显示
                 *
                 * @param posi
                 * @param listView
                 */
                public void updataView(int posi, GridView listView) {
                        int visibleFirstPosi = listView.getFirstVisiblePosition();
                        int visibleLastPosi = listView.getLastVisiblePosition();
                        if (posi >= visibleFirstPosi && posi <= visibleLastPosi) {
                                View view = listView.getChildAt(posi - visibleFirstPosi);
                                ViewHolder holder = (ViewHolder) view.getTag();
                                holder.checkBox.setVisibility(data.get(posi).isChecked()?View.VISIBLE:View.GONE);
                        }
                }
        }
}
